
<template>
	<view class="content">

		<view class="authentication_top">
			<image v-if="PreviewContract" :src="contractImg" mode="widthFix"></image>
			
			<!-- 创建合成画布 -->
			<view class="bgCoverBox">
				<canvas :style="{width:height +'px',height:width +'px'}" canvas-id="mycontract" class="canvsborder2"></canvas>
			</view>
		</view>
		
		<view class="authentication_bottom" v-if="NavAutograph" style="background:#ffe9e9" @click="agreeSign">
			<button style="color:#f00">我已阅读上述内容，同意签字>></button>
		</view>
	
		<view class="authentication_fun" v-if="Navpreservation" style="background:#fff; ">
			<button style="color:#fd972e;"  @click="SigningCompleted">签署完成，去提交>></button>
		</view>
	
		<!-- 签字弹窗 status -->
		<view class="signMask" v-if="autographStatus">
			<view class="sigh-btns">
				<button class="btn" @tap="handleCancel">取消</button>
				<button class="btn" @tap="handleReset">重写</button>
				<button class="btn" @tap="handleConfirm">确认</button>
			</view>
			<view class="sign-box">
				<canvas class="mycanvas" :style="{width:width +'px',height:height +'px'}" canvas-id="mycanvas"
					@touchstart="touchstart" @touchmove="touchmove" @touchend="touchend"></canvas>
					
				<canvas canvas-id="camCacnvs" :style="{width:height +'px',height:width +'px'}"
					class="canvsborder"></canvas>
			</view>
		</view>

		<!-- 签字弹窗 end -->

	</view>
</template>
<script>
	import { mapState, mapActions } from 'vuex';
	var x = 20;
	var y = 20;
	var tempPoint = []; //用来存放当前画纸上的轨迹点
	var id = 0;
	var type = '';
	let that;
	let canvasw;
	let canvash;
	export default {
		data() {
			return {
				contractImg: '', //合同路径
				ctx: '', //绘图图像
				points: [], //路径点集合,
				width: 0,
				height: 0,
				autographStatus: false,
				publish: false,
				PreviewContract:true,
				NavAutograph: true,
				Navpreservation:false
			}
		},
		onLoad(option) {
			that = this;
			
			//获取后台配置的协议图片
			this.getData();
			
			id = option.id;
			type = option.type;
			this.ctx = uni.createCanvasContext('mycanvas', this); //创建绘图对象
			//设置画笔样式
			this.ctx.lineWidth = 4;
			this.ctx.lineCap = 'round';
			this.ctx.lineJoin = 'round';
			uni.getSystemInfo({
				success: function(res) {
					that.width = res.windowWidth * 0.8;
					that.height = res.windowHeight * 0.85;
				}
			});
		},
		onShow() {
			
		},		
		methods: {
			getData(){
				let that = this;
				uni.request({
					url: '/user/dlxyimg',
					data: {},
					success: res => {
						res = res.res
						if (res.code === 1) {
							that.contractImg = res.data.dlxy_iamge;
						}
					}
				});
			},
			
			agreeSign() {
				this.autographStatus = true;
			},

			//触摸开始，获取到起点
			touchstart: function(e) {
				let startX = e.changedTouches[0].x;
				let startY = e.changedTouches[0].y;
				let startPoint = {
					X: startX,
					Y: startY
				};
				
				/***************************************************
				 #由于uni对canvas的实现有所不同，这里需要把起点存起来
			    ***************************************************/
				this.points.push(startPoint);

				//每次触摸开始，开启新的路径
				this.ctx.beginPath();
			},
			//触摸移动，获取到路径点
			touchmove: function(e) {
				let moveX = e.changedTouches[0].x;
				let moveY = e.changedTouches[0].y;
				let movePoint = {
					X: moveX,
					Y: moveY
				};
				this.points.push(movePoint); //存点
				let len = this.points.length;
		 	if (len >= 2) {
					this.draw(); //绘制路径
				}
				tempPoint.push(movePoint);
			},
			// 触摸结束，将未绘制的点清空防止对后续路径产生干扰
			touchend: function() {
				this.points = [];
			},
			/* ***********************************************	
					#   绘制笔迹
					#   1.为保证笔迹实时显示，必须在移动的同时绘制笔迹
					#   2.为保证笔迹连续，每次从路径集合中区两个点作为起点（moveTo）和终点(lineTo)
					#   3.将上一次的终点作为下一次绘制的起点（即清除第一个点）
					************************************************ */
			draw: function() {
				let point1 = this.points[0];
				let point2 = this.points[1];
				this.points.shift();
				this.ctx.moveTo(point1.X, point1.Y);
				this.ctx.lineTo(point2.X, point2.Y);
				this.ctx.stroke();
				this.ctx.draw(true);
			},
			handleCancel() {
				uni.navigateBack({
					delta: 1
				});
			},
			//清空画布
			handleReset: function() {
				console.log('handleReset');
				that.ctx.clearRect(0, 0, that.width, that.height);
				that.ctx.draw(true);
				tempPoint = [];
			},
			//将签名笔迹上传到服务器，并将返回来的地址存到本地
			handleConfirm: function() {
				const t = this;
				if (tempPoint.length == 0) {
					uni.showToast({
						title: '请先签名',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				
				uni.showLoading({
					title: '生成中'
				});
				
				uni.canvasToTempFilePath({
					canvasId: 'mycanvas',
					success: function(res) {
						let tempPath = res.tempFilePath;
						const ctx = uni.createCanvasContext('camCacnvs', that);
						ctx.translate(0, that.width);
						ctx.rotate((-90 * Math.PI) / 180);
						ctx.drawImage(tempPath, 0, 0, that.width, that.height);
						ctx.draw();
						
						setTimeout(() => {
							//保存签名图片到本地
							uni.canvasToTempFilePath({
									canvasId: 'camCacnvs',
									success: function(res) {
										//这是签名图片文件的本地临时地址
										
										let path = res.tempFilePath;
										//console.log(path, "保存签名图片到本地")
										
										t.autographStatus = false
										
										// 开始合成
										var _this = this;
										t.publish = true;
										t.PreviewContract = false;
										t.NavAutograph = false;
										t.Navpreservation = true;
										
										const loy = uni.createCanvasContext('mycontract', that);
									
										let imgGao = ''
										uni.getSystemInfo({
											success:function(res){
												imgGao = res.screenWidth 
											}
										})
										
										loy.drawImage(t.contractImg, 0, 0, 375 , 600);
										loy.drawImage(path, 260, 500, 100, 50);
										loy.setFontSize(16);

										loy.draw();
										setTimeout(() =>{
											uni.canvasToTempFilePath({
												canvasId: 'mycontract',
												success: function(res) {
													uni.hideLoading();
													t.contractImg = res.tempFilePath;
												}	
											})
										} ,200)
									},
									fail: err => {
									}
								},
								this
							);
						}, 200);
					}
				});
			},
			preservationImg(){
				const t = this;
				uni.downloadFile({
					url: t.contractImg,
					success: res => {
						if (res.statusCode === 200) {
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: function() {
									uni.showToast({
										title: '保存成功',
										icon: 'none',
										duration: 2000
									});
								},
								fail: function() {
									uni.showToast({
										title: '保存失败',
										icon: 'none',
										duration: 2000
									});
								}
							});
						} else {
							uni.showToast({
								title: '第三方网络错误',
								icon: 'none',
								duration: 2000
							});
						}
					}
				});
			},
			async SigningCompleted(){
				const t = this;
				
				const uploadImageRes = await this.uploadImage(t.contractImg);
				console.log("go uploadImageRes", uploadImageRes);
				
				uni.$emit('SELECT_ORDER_SIGN', uploadImageRes);
				
				uni.navigateBack({ delta: 1 });    // 返回上一页		
			},
			// 图片处理-上传图片
			async uploadImage(url) {
				const that = this;
				return new Promise((resolve, reject) => {
					that.$wanlshop.msg("上传中...");
					
					uni.request({
						url: '/wanlshop/common/uploadData',
						success: updata => {
							uni.uploadFile({
								url: updata.data.uploadurl,
								filePath: url,
								name: 'file',
								formData: updata.data.storage == 'local' ? null : updata.data.multipart,
								success: res => {
									res = JSON.parse(res.data);
									if (res.code === 1) {
										resolve(res.data);
									} else {
										that.$wanlshop.msg("上传失败"+ res.msg);
									}
								},
								fail: error =>{
									this.$wanlshop.msg("上传失败");
								}
							});
						}
					});
					
				}).catch(e => {
					console.log(e);
				});
			},
			ReSign:function(){
				this.autographStatus = true
			}
		}
	}
</script>

<style>
.authentication_top{
	width:100%;
	height:90%;
	position:fixed;
	top:0;left:0;
	right:0;
	margin:auto;
	overflow-y:scroll;
	padding-bottom:40rpx;
}

.authentication_top image
{
	width:100%;
	display:inline-block
}

.authentication_bottom
{
	width:100%;
	height:10%;
	position:fixed;
	bottom:0;
	left:0;
	right:0;
	margin:auto;
	display:flex;
	flex-direction:column;
	justify-content:center;
	align-items:center;
	background:#ffe9e9
}

.authentication_bottom button{
	background:0 0;
	border:none;
	font-size:15px;
	color:red;
	width:100%;
	text-align:center
}

.authentication_bottom button:after{
	display:none
}

.authentication_fun{
	width:100%;
	height:10%;
	position:fixed;
	bottom:30rpx;
	left:0;
	right:0;
	margin:auto;
	display:flex;
	flex-direction:row;
	justify-content:center;
	align-items:center;
	background:#ffe9e9;
	padding:0 3%;
	width:90%;
	border-radius:50px;
	box-shadow:0 3px 13px rgba(0,0,0,.2);
	border:4px solid #fd972e;
	box-sizing:border-box;
}

.authentication_fun button{
	border:none;
	font-size:15px;
	background:0 0;
	width:100%;
	text-align:center
}

.authentication_fun button:after{
	display:none
}

.signMask{
	width:100%;
	height:100%;
	background:#fff;
	position:fixed;
	top:0;
	bottom:0;
	left:0;
	right:0;
	flex-direction:row
}

.sign-box,.signMask{
	margin:auto;
	display:flex
}

.sign-box{
	width:80%;
	height:90%;
	flex-direction:column;
	text-align:center
}

.sigh-btns,.sign-view{
	height:100%
}

.sigh-btns{
	margin:auto;
	display:flex;
	flex-direction:column;
	justify-content:space-around
}

.btn{
	margin:auto;
	padding:8rpx 40rpx;
	font-size:14px;
	transform:rotate(90deg);
	border:1rpx solid grey
}

.mycanvas{
	margin:auto 0rpx;
	background-color:#ececec
}

.canvsborder{
	border:1rpx solid #333;
	position:fixed;
	top:0;
	left:10000rpx
}

.bgCoverBox{
	width:100%;
	height:auto
}
.canvsborder2{
	height:700px!important
}
	
</style>


